package com.weishuang.monitor.leader.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.util.pattern.PathPatternParser;

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");

        //前端对接使用
        config.addAllowedOrigin("http://localhost:7070");
        config.addAllowedOrigin("http://127.0.0.1:7070");
        config.addAllowedOrigin("http://121.41.2.120:8081");
        config.setAllowCredentials(true);

        //yapi接口测试使用
//        config.addAllowedOrigin("*");


        CorsConfiguration apiConfig = new CorsConfiguration();
        apiConfig.addAllowedMethod("*");
        apiConfig.addAllowedHeader("*");
        apiConfig.addAllowedOrigin("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/leader/**", config);
        source.registerCorsConfiguration("/login", config);
        source.registerCorsConfiguration("/logout", config);

        source.registerCorsConfiguration("/api/**", apiConfig);
        return new CorsFilter(source);
    }
}
